package com.lzy.business.controller.order;

import com.github.pagehelper.PageInfo;
import com.lzy.business.controller.BaseController;
import com.lzy.business.facade.OrderProductFacade;
import com.lzy.business.request.OrderProductImageRequest;
import com.lzy.business.request.OrderProductRequest;
import com.lzy.business.response.OrderProductResponse;
import com.lzy.framework.component.PageBean;
import com.lzy.framework.core.ensure.Ensure;
import com.lzy.framework.core.excel.SimpleExcelExportUtils;
import com.lzy.framework.core.orm.db.Pager;
import com.lzy.framework.core.output.Result;
import com.lzy.framework.core.utils.CollectionUtils;
import com.lzy.framework.core.utils.DozerUtils;
import com.lzy.framework.core.utils.WebUtils;
import com.lzy.product.constants.BusinessType;
import com.lzy.product.dtos.OrderProductDto;
import com.lzy.product.dtos.OrderProductImageDto;
import com.lzy.web.exception.GenericException;
import com.lzy.web.response.excel.OrderListExportResponse;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

/**
 * 产品订单
 *
 * @author swt
 */
@Controller
@RequestMapping("admin/order/product")
public class OrderProductController extends BaseController {
    private static final Logger logger = LoggerFactory.getLogger(OrderProductController.class);

    @Resource
    private OrderProductFacade orderProductFacade;

    /**
     * 产品订单：tab页面
     *
     * @param status 状态
     * @param model
     * @return
     */
    @RequestMapping(value = "/{status}", method = RequestMethod.GET)
    public String orderList(@PathVariable("status") Integer status, Model model) {
        model.addAttribute("status", status);
        return "order/product/order_list";
    }

    /**
     * 跳转至手动确认线下支付过的待支付订单页面
     *
     * @param orderId
     * @param model
     * @return
     */
    @RequestMapping(value = "/offline/{orderId}", method = RequestMethod.GET)
    public String offline(@PathVariable("orderId") Integer orderId, Model model) {
        model.addAttribute("orderId", orderId);
        return "order/product/order_offline";
    }

    /**
     * 手动确认线下支付过的待支付订单信息提交
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/offline/submit", method = RequestMethod.POST)
    @ResponseBody
    public Result offlineSubmit(OrderProductImageRequest request) {
        Ensure.that(request).isNotNull("04000001");
        if (request.getOrderId() != null && request.getImages() != null) {
            orderProductFacade.offlineSubmit(DozerUtils.map(request, OrderProductImageDto.class));
        }
        return new Result();
    }

    /**
     * 查询产品订单列表
     *
     * @param request 查询条件
     * @return
     */
    @RequestMapping(value = "orderList/{status}", method = RequestMethod.GET)
    @ResponseBody
    public PageBean orderProductList(@PathVariable("status") Integer status, OrderProductRequest request) {
        Ensure.that(request).isNotNull("04000001");
        Pager pager = new Pager();
        pager.setPageSize(request.getPageSize());
        pager.setPageNum(request.getPageNum());
        if (null != status && status != -1) {
            request.setStatus(status);
        } else {
            request.setStatus(null);
        }
        request.setType(BusinessType.OrderProductType.PRODUCT.getCode());
        PageInfo<OrderProductDto> pageInfo = orderProductFacade.orderProductList(pager, DozerUtils.map(request, OrderProductDto.class));
        if (pageInfo != null) {
            return new PageBean<>(pageInfo.getTotal(), DozerUtils.maps(pageInfo.getList(), OrderProductResponse.class));
        }
        return null;
    }

    /**
     * 查看订单详情
     *
     * @param model
     * @param orderId 订单ID
     * @return
     */
    @RequestMapping(value = "orderDetail/{orderId}", method = RequestMethod.GET)
    public String orderProductDetail(Model model, @PathVariable("orderId") String orderId) {
        OrderProductDto orderProductDto = orderProductFacade.orderProductDetail(Long.parseLong(orderId));
        model.addAttribute("orderProductDto", orderProductDto);
        return "order/product/order_view";
    }

    /**
     * 导出订单
     *
     * @param request
     * @param response
     * @param listRequest
     */
    @RequestMapping(value = "/exportOrderList")
    public void exportOrderList(HttpServletRequest request, HttpServletResponse response, OrderProductRequest listRequest) {
        try {
            Pager pager = new Pager();
            pager.setPageSize(10000);
            OrderProductDto dto = DozerUtils.map(listRequest, OrderProductDto.class);
            dto.setType(BusinessType.OrderProductType.PRODUCT.getCode());
            PageInfo<OrderProductDto> pageInfo = orderProductFacade.orderProductList(pager, dto);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            List<OrderProductDto> list = pageInfo.getList();
            if (CollectionUtils.isNotEmpty(list)) {
                if (list.size() > 10000)
                    throw new GenericException("导出数据量过大,请重新输入检索条件,分批导出！");
                LinkedList<OrderListExportResponse> voList = new LinkedList<>();
                OrderListExportResponse vo;
                for (OrderProductDto orderProductDto : list) {
                    vo = new OrderListExportResponse();
                    BeanUtils.copyProperties(orderProductDto, vo);
                    voList.add(vo);
                }
                SimpleExcelExportUtils excelExportService = new SimpleExcelExportUtils();
                HSSFWorkbook wb = new HSSFWorkbook();
                if (voList != null && voList.size() > 0) {
                    wb = excelExportService.generateExcel(voList);
                }
                String fileName = "产品订单" + sdf.format(new Date()) + ".xls";
                // 设定输出文件头
                WebUtils.prepareDownloadFile(fileName, "application/msexcel", request, response);
                OutputStream out = response.getOutputStream();
                wb.write(out);
                out.close();
            } else {
                logger.error("没有可执行数据：产品订单数据导出EXCEL失败！");
            }
        } catch (Exception e) {
            logger.error("产品订单数据导出EXCEL失败！", e);
            throw new GenericException("产品订单数据导出EXCEL失败");
        }
    }

    /**
     * 查看产品订单详情（后台使用）
     * @param orderId 订单ID
     * @return
     */
    @RequestMapping(value = "detail/{orderId}", method = RequestMethod.GET)
    @ResponseBody
    public Result orderProductDetail(@PathVariable("orderId") String orderId) {
        Result result = new Result();
        OrderProductDto orderProductDto = orderProductFacade.orderProductDetail(Long.parseLong(orderId));
        result.setResult(orderProductDto);
        return result;
    }

}
